jQuery.event.special.longtouch = {
    setup: function (data, namespaces) {
        var elem = this, $elem = jQuery(elem);

        /* Android's horrificly bad browser does not support window.Touch so we'll resort to UA sniffing */
        var ua = navigator.userAgent.toLowerCase();
        var isAndroid = ua.indexOf("android") > -1;

        if (window.Touch || isAndroid) {
            $elem.bind('touchstart', jQuery.event.special.longtouch.onTouchStart);
            $elem.bind('touchmove', jQuery.event.special.longtouch.onTouchMove);
            $elem.bind('touchend', jQuery.event.special.longtouch.onTouchEnd);
        }
    },

    click: function (event) {
        event.type = "longtouch";
        jQuery.event.handle.apply(this, arguments);
    },

    teardown: function (namespaces) {
        if (window.Touch) {
            $elem.unbind('touchstart', jQuery.event.special.longtouch.onTouchStart);
            $elem.unbind('touchmove', jQuery.event.special.longtouch.onTouchMove);
            $elem.unbind('touchend', jQuery.event.special.longtouch.onTouchEnd);
        } 
    },

    onTouchStart: function (e) {
        debbugwrite('onTouchStart');

        var event = e.originalEvent;
        this.lastContext = e.originalEvent;
        this.lastContext.target = event.originalTarget;
        this.lastContext.pageX = event.touches[0].pageX;
        this.lastContext.pageY = event.touches[0].pageY;
        this.lastContext.clientX = event.touches[0].clientX;
        this.lastContext.clientY = event.touches[0].clientY;

        this.moved = false;
        window.longTouchID = 1;
        $(this).delay(500).queue(function (next) {
            window.longTouchID = 0;
            next();
        });
        $(this).addClass('touchactive');
    },

    onTouchMove: function (e) {
        this.moved = true;

        $(this).removeClass('touchactive');
    },

    onTouchEnd: function (event) {
        debbugwrite('onTouchEnd: ' + window.longTouchID + " " + this.moved);
        if (!this.moved) {
            if (window.longTouchID == 1) {
                event.type = "touchclick";
            }
            else {
                event.type = "longtouch";
            }
            window.longTouchID = 2;
            event.vc_context = this.lastContext;
            event.vc_sender = event.target;
            jQuery.event.handle.apply(this, arguments)
        }

        $(this).removeClass('touchactive');
    }
};